package org.czf.zk;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class ZookeeperApi {

    @Autowired
    private CuratorFramework client ;


    /**
     * https://juejin.cn/post/6844903818090512397?searchId=20240603105009A1D300662608DB504DC8
     * @throws Exception
     */

    public void create () throws Exception {
        // 创建一个持久化节点，断开连接时不会自动删除
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/path1");

    }


    public void exists () throws Exception {
        // 判断节点是否存在，path2不存在所以stat2是null
        Stat stat1 = client.checkExists().forPath("/path1");
        log.info("{}", JSON.toJSONString(stat1));
        Stat stat2 = client.checkExists().forPath("/path2");
        System.out.println(stat2);
    }

    public void setData () throws Exception {
        // 设置节点数据
        client.setData().forPath("/path1", "data1".getBytes(StandardCharsets.UTF_8));
    }

    public void createAndSet () throws Exception {
        // 创建一个持久化节点并设置节点数据
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                .forPath("/path3","data3".getBytes(StandardCharsets.UTF_8));
    }

    public void getData () throws Exception {
        // 查询节点数据
        byte[] data = client.getData().forPath("/path3");
        System.out.println(new String(data,StandardCharsets.UTF_8));
    }

    public void delete () throws Exception {
        // 删除节点
        client.delete().guaranteed().deletingChildrenIfNeeded().forPath("/path3");
    }

    public void readLock () throws Exception {
        // 读写锁-读
        InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client,"/lock-read");
        lock.readLock().acquire();
        System.out.println("获取-ReadLock");
        lock.readLock().release();
    }

    public void writeLock () throws Exception {
        // 读写锁-写
        InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client,"/lock-write");
        lock.writeLock().acquire();
        System.out.println("获取-WriteLock");
        lock.writeLock().release();
    }
}